package com.yanqu.road.web.controller.game;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.enums.eActivityType;
import com.yanqu.road.entity.enums.eChannelType;
import com.yanqu.road.entity.enums.ePlatformForbiddenType;
import com.yanqu.road.entity.platform.PlatformForbidden;
import com.yanqu.road.entity.player.OpenInvitedData;
import com.yanqu.road.entity.player.UserInfo;
import com.yanqu.road.entity.servercenter.ServerInfo;
import com.yanqu.road.entity.web.HttpGameWebParam;
import com.yanqu.road.entity.web.WebLoginParam;
import com.yanqu.road.logic.bussiness.log.LogBussiness;
import com.yanqu.road.logic.bussiness.player.UserBussiness;
import com.yanqu.road.logic.config.ChannelConfig;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.logic.redis.RedisManger;
import com.yanqu.road.logic.redis.RedisUserServerList;
import com.yanqu.road.player.PlayerControl;
import com.yanqu.road.reids.subpub.eRedisChannelType;
import com.yanqu.road.server.helper.SignHelper;
import com.yanqu.road.server.manger.*;
import com.yanqu.road.server.manger.activity.NormalActivityMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.utils.ConfigHelper;
import com.yanqu.road.utils.MD5Security;
import com.yanqu.road.utils.RandomHelper;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.http.HttpHelper;
import com.yanqu.road.utils.net.ServerNetConfig;
import com.yanqu.road.utils.string.StringUtils;
import com.yanqu.road.web.WebServer;
import com.yanqu.road.web.controller.BaseGameHttpServlet;
import com.yanqu.road.web.mgr.LogMgr;
import com.yanqu.road.web.mgr.LoginPlayerQueueMgr;
import com.yanqu.road.web.mgr.UserIdMgr;
import com.yanqu.road.web.util.AllocateAddress;
import com.yanqu.road.web.util.IpAddressHelper;
import com.yanqu.road.webservice.invoke.GameWebServiceInvoke;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@WebServlet(urlPatterns = "/login")
public class WebLogin extends BaseGameHttpServlet {

    private Logger logger = LogManager.getLogger(WebLogin.class.getName());
    private final int LOGIN_CODE_DEFAULT = 0;          //初始状态码
    private final int LOGIN_CODE_SUCCESS = 1;          //成功状态码
    private final int LOGIN_CODE_REGISTER = 2;         //注册状态码
    private final int LOGIN_CODE_SERVER_MAINTAIN = 3;  //登录受限区服维护状态码

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpGameWebParam httpGameWebParam = super.parseRequest(request);
        webLogin(request, response, httpGameWebParam);
    }

    private void webLogin(HttpServletRequest request, HttpServletResponse response, HttpGameWebParam httpGameWebParam) {
        JSONObject paramObj = httpGameWebParam.getParamObj();
        String param = httpGameWebParam.getParam();
        String language = httpGameWebParam.getLanguage();

        JSONObject resultObj;
        try {
            String ip = IpAddressHelper.getIpAddr(request);
            WebLoginParam loginParam = new WebLoginParam(paramObj);

            //刷接口的，过滤下，淦
            ServerInfo serverInfo = ServerListMgr.getServerInfo(WebServer.getInstance().getServerId());
            if(null != serverInfo){
                if(serverInfo.getServerType() != ServerListMgr.SERVER_TYPE_DEBUG
                    && serverInfo.getServerType() != ServerListMgr.SERVER_TYPE_REVIEW
                ){//测试服、提审服可能有多配置
                    if(WebServer.getInstance().getServerId() != loginParam.getServerId()){//还没有合服，这两个值一定是一样的
                        sendMessage(response, getResultObj(GameErrorCode.E_REQUEST_ARGUMENT_ERROR, language).toJSONString());
                        logger.error("注册刷接口,uid:{},openId:{},ip:{}", loginParam.getPlatformUserId(),loginParam.getOpenId(), ip);
                        return;
                    }
                }
            }

            if (!ServerListMgr.canLogin(WebServer.getInstance().getServerId(), ip, false,loginParam.getPlatformUserId())) {//维护状态
                sendMessage(response, getResultObj(GameErrorCode.E_SERVER_MAINTAIN, language).toJSONString());
                return ;
            }
            //校验当前排队人数
//            long onlineCount = RedisServerOnlineCount.getOnlineCount(WebServer.getInstance().getServerId());
            long onlineCount = 0;

            // 铁人三项活动判断
            if (serverInfo.getServerType() == ServerListMgr.SERVER_TYPE_ACTIVITY) {
                // 如果是活动服
                if (!CnActivityMgr.isCnActivityUser(loginParam.getServerId() ,loginParam.getPlatformUserId())) {
                    resultObj = getResultObj(GameErrorCode.E_NO_IN_CN_ACTIVITY_USER, language);
                    sendMessage(response, resultObj.toJSONString());
                    logger.error("不在活动名单内, uid : {}", loginParam.getPlatformUserId());
                    return;
                }
            }

            if (onlineCount < serverInfo.getMaxOnlineCount() || !serverInfo.isOpenLoginQueue()) {
                //登录校验
                String verifyResult = verifyAccount(loginParam, language);
                if(!StringUtils.isNullOrEmpty(verifyResult)){
                    sendMessage(response, verifyResult);
                }else{
                    String result;
                    synchronized (UserIdMgr.getOpenIdLocker(loginParam.getOpenId())) {
                        //预创角
                        if(ServerListMgr.isPreRole(serverInfo.getServerId())){
                            result = preLogin(loginParam, ip, language);
                        }else{
                            //预创的转移
                            preCheck(loginParam);
                            result = checkLogin(loginParam, ip, language);
                        }
                    }
                    sendMessage(response, result);
                }
                LoginPlayerQueueMgr.removeOpenId(loginParam.getOpenId());
            } else {
                LoginPlayerQueueMgr.addOpenId(loginParam.getOpenId(), System.currentTimeMillis());
                sendMessage(response, getResultObj(GameErrorCode.E_USER_LOGIN_ONLINE_FULL, language).toJSONString());
            }
        } catch (Exception e) {
            resultObj = getResultObj(GameErrorCode.E_REQUEST_ARGUMENT_ERROR, language);
            sendMessage(response, resultObj.toJSONString());
            logger.error("Login json格式出错！ json 字符串param为{}", param, e);
        }
    }

    /**
     * 设置邀请码
     */
    private void setOpenInvitedCode(WebLoginParam param, UserInfo userInfo) {
        // 是否新openId
    //    GameServer.getSqlCommandExecutor().execute(() -> {
            logger.info("user {}, invitedCode: {}",userInfo == null ? "null":String.valueOf(userInfo.getUserId()),param == null ? "null":param.getInvitedCode());
            if (param == null || userInfo == null || StringUtils.isNullOrEmpty(param.getInvitedCode())) return;
            try {
              /*  Map<Long, Long> dataMap = new LogUserInfoDaoImpl().getUserServerListRegisterTime(param.getOpenId());
                for (Map.Entry<Long, Long> entry : dataMap.entrySet()) {
                    long tmpServerId = entry.getKey();
                    long tmpRegisterTime = entry.getValue() / 1000;
                    if (param.getServerId() != tmpServerId && userInfo.getRegisterTime() > tmpRegisterTime) {
                        return; // 不是新openId
                    }
                }*/
                // 设置邀请码
                if (!RedisManger.getRedisUtil().exists("PLAYER-INVITED-" + param.getOpenId())) {
                    OpenInvitedData data = new OpenInvitedData(param.getOpenId(), param.getInvitedCode(), userInfo.getRegisterTime());
                    //   new OpenInvitedDataDaoImpl().add(data);
                    JSONObject object = new JSONObject();
                    object.put("openId",data.getOpenId());
                    object.put("invitedCode",data.getInvitedCode());
                    object.put("registerTime",data.getRegisterTime());
                    RedisManger.getRedisUtil().setString("PLAYER-INVITED-" + data.getOpenId(),JSON.toJSONString(object));
                }
            } catch (Exception e) {
                logger.error("add invited code error",e);
            }
     //   });


      //  new OpenInvitedDataDaoImpl().update(data); // insert带ignore，需要再次update
    }

    private String verifyAccount(WebLoginParam loginParam, String language){
        String userID = loginParam.getOpenId();
        String token = loginParam.getToken();
        if(!StringUtils.isNullOrEmpty(token)) {
            SortedMap<String, String> paramMap = new TreeMap<>();
            paramMap.put("userID", userID);
            paramMap.put("token", token);
            String sign;
            if(isAppChannel(loginParam.getAppId())
                    && !StringUtils.isNullOrEmpty(ChannelConfig.APP_LOGIN_VERIFY_URL)
                    && !StringUtils.isNullOrEmpty(ChannelConfig.APP_SECRET_CONFIG)) {
                sign = SignHelper.getSign(paramMap, ChannelConfig.APP_SECRET_CONFIG);
            }else {
                sign = SignHelper.getSign(paramMap, AppKeyMgr.getAndroidAppSecret());
            }
            paramMap.put("sign", sign);
            String result;
            if(isAppChannel(loginParam.getAppId()) && !StringUtils.isNullOrEmpty(ChannelConfig.APP_LOGIN_VERIFY_URL)){
                result = HttpHelper.doGet(ChannelConfig.APP_LOGIN_VERIFY_URL, paramMap, "UTF-8");
            }else {
                result = HttpHelper.doGet(AppKeyMgr.getPlatformBaseUrl() + "/user/verifyAccount", paramMap, "UTF-8");
            }

            logger.info("verifyAccount response:{}", result);
            if(StringUtils.isNullOrEmpty(result)){
                JSONObject tempObj = getResultObj(GameErrorCode.E_PLATFORM_LOGIN_VERIFY_ERROR, language);
                return tempObj.toJSONString();
            }
            JSONObject resultObj = JSON.parseObject(result);
            if (1 != resultObj.getIntValue("state")) {
                JSONObject tempObj = getResultObj(GameErrorCode.E_PLATFORM_LOGIN_VERIFY_ERROR, language);
                return tempObj.toJSONString();
            } else {//远程登录校验成功
                return "";
            }
        }else {//不用远程登录校验
            return "";
        }
    }

    private void preCheck(WebLoginParam loginParam){
        UserInfo userInfo;
        userInfo = UserBussiness.getPreUserInfosByOpenIdFull(loginParam.getOpenId(), loginParam.getServerId());
        if(userInfo != null){
            UserInfo mainUserInfo = UserBussiness.getUserInfoByOpenIdAndServerId(loginParam.getOpenId(), loginParam.getServerId());
            if(mainUserInfo == null){
                userInfo = UserBussiness.registerFromPre(userInfo);
            }
        }
    }


    private String preLogin(WebLoginParam loginParam, String ip, String language){
        try {
            UserInfo userInfo;
            long serverId = Long.parseLong(ConfigHelper.getValue("serverId"));
            userInfo = UserBussiness.getPreUserInfosByOpenIdAndServerId(loginParam.getOpenId(), loginParam.getServerId());
            if(userInfo == null){
                if (ServerListMgr.isRegisterPreCountMax(serverId)) {
                    return getResultObj(GameErrorCode.E_REGISTER_PRE_SERVER_MAX, language).toJSONString();
                }
//                int createPreCount = UserBussiness.getUserCountByOpenId(loginParam.getOpenId());
                Set<String> userRegisterServerList =
                        RedisManger.getRedisUtil().zmember("PLAYERFISHSERVER"+ "_" + loginParam.getOpenId(),0,System.currentTimeMillis()/1000);
                int createPreCount = userRegisterServerList.size();
                if (createPreCount >= GameConfig.CREATE_PRE_ROLE_USER_COUNT) {
                    return getResultObj(GameErrorCode.E_REGISTER_PRE_USER_MAX, language).toJSONString();
                }

                long userId = UserIdMgr.getNextUserId();
                long userAliasId = UserIdMgr.getUserAliasId(userId);

                // 默认隐藏VIP及地址
                int hideVipAddress = getDefaultSetting();
                userInfo = UserBussiness.registerPre(loginParam, userId, userAliasId, hideVipAddress);
//                UserBussiness.registerPreServer(loginParam.getOpenId(), userId, serverId);
                return getResultObj(0, userInfo, true, language, "", "").toJSONString();
            }else{
                if(StringUtils.isNullOrEmpty(userInfo.getNickName())){
                    return getResultObj(0, userInfo, true, language, "", "").toJSONString();
                }else{
                    return getResultObj(0, userInfo, false, language, "", "").toJSONString();
//                    return getResultObj(GameErrorCode.E_REGISTER_PRE_USER_DONE, language).toJSONString();
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return getResultObj(GameErrorCode.E_USER_LOGIN_UNKNOWN_ERROR, language).toJSONString();
    }

    private String checkLogin(WebLoginParam loginParam, String ip, String language) {
        try {
            int result = LOGIN_CODE_DEFAULT;
            UserInfo userInfo;
            long serverId = Long.parseLong(ConfigHelper.getValue("serverId"));
            int channelId = ServerListMgr.getChannelId(serverId);

//            if (channelId == eChannelType.MainLand.getValue() || channelId == eChannelType.MainLandBusiness.getValue() || channelId == eChannelType.MainLandInnerTest.getValue()) {
            if (serverId > 20100000 && serverId <= 20199999) {
                List<UserInfo> userInfoList = UserBussiness.getUserInfosByOpenIdAndServerId(loginParam.getOpenId(), loginParam.getServerId());
                if (userInfoList.size() == 1) {
                    // 如果只有一个角色 就直接进入这个角色
                    userInfo = userInfoList.get(0);
                } else if (userInfoList.size() > 1) {
                    userInfo = null;

                    // 如果是H5版本进的游戏
                    if (loginParam.getAppId().equals("37h5_cn")) {

                        // 先看是否有绑定H5的角色
                        for (UserInfo u : userInfoList) {
                            if (u.getUserMark().equals("37h5_cn")) {
                                userInfo = u;
                                break;
                            }
                        }

                        // 如果还没绑定角色 取赚速最高的那个绑定
                        if (userInfo == null) {
                            Collections.sort(userInfoList, new Comparator<UserInfo>() {
                                @Override
                                public int compare(UserInfo o1, UserInfo o2) {
                                    int result = o1.getEarnSpeed().compareTo(o2.getEarnSpeed());
                                    if (result > 0) {
                                        return -1;
                                    } else if (result == 0) {
                                        return 0;
                                    } else {
                                        return 1;
                                    }
                                }
                            });
                            userInfo = userInfoList.get(0);
                            UserBussiness.updateUserMark(userInfo.getUserId(), "37h5_cn");
                        }

                    } else {
                        // 如果非H5版本进的游戏 则选择跟客户端同平台的
                        for (UserInfo u : userInfoList) {
                            if (u.getPhonePlatform() == loginParam.getPhonePlatform()) {
                                userInfo = u;
                                break;
                            }
                        }
                    }

                } else {
                    userInfo = null;
                }
            } else if (eChannelType.isMainLandChannel(channelId) && serverId > 20199999 && serverId <= 30100012) {
                // 区分安卓ios角色
                userInfo = UserBussiness.getUserInfoByOpenIdAndPhonePlatform(loginParam.getOpenId(), loginParam.getPhonePlatform(), loginParam.getServerId());
            } else {
                userInfo = UserBussiness.getUserInfoByOpenIdAndServerId(loginParam.getOpenId(), loginParam.getServerId());
            }


            // 检查游戏服内存：内存过高 && 不在内存内的玩家 => 提示爆满、无法登录
            int ret = GameWebServiceInvoke.loginCheckGameServerMemory(userInfo == null ? 0L : userInfo.getUserId());
            if (ret != 0) {
                return getResultObj(ret, language).toJSONString();
            }

            if (null == userInfo) {//新用户，注册
//                if (Objects.equals("mangotv", loginParam.getAppId()) || Objects.equals("coolpad", loginParam.getAppId())) {//芒果tv不让注册
//                    return getResultObj(GameErrorCode.E_SERVER_APPID_CLOSE_REGISTER, language).toJSONString();
//                }
                if (ServerListMgr.isAppIdLimitRegister(loginParam.getAppId())) {
                    return getResultObj(GameErrorCode.E_SERVER_APPID_CLOSE_REGISTER, language).toJSONString();
                }
                ServerInfo serverInfo = ServerListMgr.getServerInfo(WebServer.getInstance().getServerId());
                if (serverInfo != null) {
                    if ((eChannelType.isMainLandChannel(channelId) || channelId == eChannelType.MainLandInnerTest.getValue()) && serverInfo.isCreateRoleLimit()) {
                        logger.info("server register is full,openId:{},platformUserId:{},appId;{},phonePlatform:{},ip:{}",
                                loginParam.getOpenId(), loginParam.getPlatformUserId(), loginParam.getAppId(), loginParam.getPhonePlatform(), ip);
                        return getResultObj(GameErrorCode.E_SERVER_REGISTER_IS_FULL, language).toJSONString();
                    }
                }

                if (!ServerListMgr.canLogin(WebServer.getInstance().getServerId(), ip, false,loginParam.getPlatformUserId())) {//维护状态
                    return getResultObj(GameErrorCode.E_SERVER_MAINTAIN, language).toJSONString();
                } else {
                    long userId = UserIdMgr.getNextUserId();
                    long userAliasId = UserIdMgr.getUserAliasId(userId);

                    // 默认隐藏VIP及地址
                    int hideVipAddress = getDefaultSetting();
                    userInfo = UserBussiness.register(loginParam, userId, userAliasId, hideVipAddress);
                    result = LOGIN_CODE_REGISTER;
                    if (null != userInfo) {
                        UserIdMgr.addRegisterCount(1);
                        LogMgr.addUserInfo(WebServer.getInstance().getServerId(), userInfo.getUserId(), loginParam.getOpenId(), userInfo.getNickName(),
                                System.currentTimeMillis(), "", ip, loginParam.getPhonePlatform(), loginParam.getServerId());
                        //创建账号埋点
                        //WebDataAnalyticsMgr.createCount(userInfo);
                        DataAnalyticsMgr.createCount(userInfo);
                    }
                }
                // 注册时设置邀请码
                try {
                    setOpenInvitedCode(loginParam, userInfo);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            if (null == userInfo) {//注册保存到数据库失败
                return getResultObj(GameErrorCode.E_USER_REGISTER_SAVE_DB_ERROR, language).toJSONString();
            } else {
                // 非白名单ip 需要判断是否封禁账号 当 BlackListEndTime = 3的时候 为被接管状态
                if (!WhiteIpMgr.isPlayerWhiteIp(ip)) {
                    if (!ForbiddenMgr.canLogin(ip)) {
                        return getResultObj(GameErrorCode.E_USER_FORBIDDEN, language).toJSONString();
                    }
                    if (userInfo.getBlackListEndTime() > System.currentTimeMillis()) {
                        JSONObject resultObj = getResultObj(GameErrorCode.E_USER_FORBIDDEN, language);
                        resultObj.put("forbiddenEndTime", userInfo.getBlackListEndTime());
                        return resultObj.toJSONString();
                    } else if (userInfo.getBlackListEndTime() == 3) {
                        JSONObject resultObj = getResultObj(GameErrorCode.E_ROLE_WAS_TASK_OVER, language);
                        return resultObj.toJSONString();
                    } else if (userInfo.getBlackListEndTime() == 4) {
                        JSONObject resultObj = getResultObj(GameErrorCode.E_DEDUCT_INGOTS_NO_ENOUGH_FORBIDDEN, language);
                        return resultObj.toJSONString();
                    }

                    if (ForbiddenMgr.isPlatformForbidden(userInfo.getPlatformUserId(), ePlatformForbiddenType.LOGIN.getType())) {
                        PlatformForbidden forbidden = ForbiddenMgr.getPlatformForbidden(userInfo.getPlatformUserId(), ePlatformForbiddenType.LOGIN.getType());
                        if (forbidden != null) {
                            long forbiddenTime = forbidden.getForbiddenTime();
                            JSONObject resultObj = getResultObj(GameErrorCode.E_USER_FORBIDDEN, language);
                            resultObj.put("forbiddenEndTime", forbiddenTime);
                            return resultObj.toJSONString();
                        }
                    }
                }

                updateUserPlatformUserId(loginParam, userInfo);      //更新玩家平台用户编号
                if (LOGIN_CODE_REGISTER != result) {
                    //老用户，到gameServer 请求是否可以登陆
                    if (!ServerListMgr.canLogin(WebServer.getInstance().getServerId(), ip, userInfo.isAdmin(),userInfo.getPlatformUserId())) {
                        result = LOGIN_CODE_SERVER_MAINTAIN;
                    } else {
                        result = LOGIN_CODE_SUCCESS;
                    }
                }
                String signKey = RandomStringUtils.randomAlphanumeric(32);
                String signValue = RandomStringUtils.randomAlphanumeric(32);
                int randomInt = new RandomHelper().next(999);

                switch (result) {
                    case LOGIN_CODE_SUCCESS:
                        Set<String> redisServerIds = RedisUserServerList.getPlayerServerList(userInfo.getOpenId());
                        if (redisServerIds == null || redisServerIds.isEmpty()) {
                            List<Long> userServerIds = LogBussiness.getUserServerListByOpenId(userInfo.getOpenId());
                            for (Long userServerId : userServerIds) {
                                RedisUserServerList.addToRegisterServerList(userInfo.getOpenId(), userServerId);
                            }
                        }
                        RedisUserServerList.addToRegisterServerList(userInfo.getOpenId(), loginParam.getServerId());
                        // 去用户中心记录用户ip
                        GameWebServiceInvoke.recordUserIp(userInfo.getUserId(), ip);
                        GameWebServiceInvoke.recordUserSign(userInfo.getUserId(), signKey, signValue + "_" + randomInt);
                        //存储玩家包体ID
                        UserMgr.recordUserPackageMark(userInfo.getUserId(), loginParam.getPackageMark());
                        checkPlatformMessage(userInfo.getPlatformUserId());
                        return getResultObj(0, userInfo, false, language, signKey, signValue + randomInt).toJSONString();
                    case LOGIN_CODE_SERVER_MAINTAIN:
                        return getResultObj(GameErrorCode.E_SERVER_MAINTAIN, language).toJSONString();
                    case LOGIN_CODE_REGISTER:
                        // 新用戶
                        RedisUserServerList.addToRegisterServerList(userInfo.getOpenId(), WebServer.getInstance().getServerId());
                        GameWebServiceInvoke.recordUserIp(userInfo.getUserId(), ip);
                        GameWebServiceInvoke.recordUserSign(userInfo.getUserId(), signKey, signValue + "_" + randomInt);
                        checkPlatformMessage(userInfo.getPlatformUserId());
                        return getResultObj(0, userInfo, true, language, signKey, signValue + randomInt).toJSONString();
                    default:
                        return getResultObj(GameErrorCode.E_USER_LOGIN_UNKNOWN_ERROR, language).toJSONString();
                }
            }
        } catch (Exception e) {
            logger.error("Login error:", e);
            return getResultObj(GameErrorCode.E_USER_LOGIN_UNKNOWN_ERROR, language).toJSONString();
        }
    }

    private void checkPlatformMessage(String platformUserId) {
        try {
            int today = Integer.valueOf(DateHelper.getPyyyyMMddDateString(System.currentTimeMillis() / 1000));
            String message = platformUserId + ";" + today;
            if(RedisManger.getRedisUtil().exists(eRedisChannelType.LunTanSignIn.getMessageKey(message))){
                GameWebServiceInvoke.addUserBehavior(platformUserId, eRedisChannelType.LunTanSignIn.getType());
                logger.info("platformUserId : {} signIn", platformUserId);
            }
            //有活动才处理
            List<ActivityInfo> activityInfoList = NormalActivityMgr.getOpenActivityInfoList(eActivityType.Zfb.getValue(), 1);
            if(activityInfoList.size() > 0){
                message = platformUserId + ";" + eRedisChannelType.ZfbIndex.getType();
                if(RedisManger.getRedisUtil().exists(eRedisChannelType.ZfbIndex.getMessageKey(message))) {
                    GameWebServiceInvoke.addUserBehavior(platformUserId, eRedisChannelType.ZfbIndex.getType());
                }
            }
        }catch (Exception e){
            logger.error("checkPlatformMessage error:", e);
        }
    }

    /**
     * 更新玩家平台用户编号
     * @param loginParam
     * @param userInfo
     */
    private void updateUserPlatformUserId(WebLoginParam loginParam, UserInfo userInfo){
        if(null == userInfo){
            return;
        }
        if(StringUtils.isNullOrEmpty(userInfo.getPlatformUserId()) && !StringUtils.isNullOrEmpty(loginParam.getPlatformUserId())){
            //更新数据库数据
            if(UserBussiness.updateUserPlatformUserId(userInfo.getUserId(), loginParam.getPlatformUserId(), loginParam.getPlatformUserName())){
                GameWebServiceInvoke.updateUserPlatformUserId(userInfo.getUserId(), loginParam.getPlatformUserId(), loginParam.getPlatformUserName());
            }
        }
    }

    private JSONObject getResultObj(int ret, UserInfo userInfo, boolean isRegister, String language, String signKey, String signValue){
        JSONObject resultObj = super.getResultObj(ret, language);
        if(0 == ret){
            if(null != userInfo){
                resultObj.put("userId", userInfo.getUserId());
                resultObj.put("nickName", userInfo.getNickName());
                resultObj.put("ququecount", LoginPlayerQueueMgr.getOpenIndex(userInfo.getOpenId()));
                String address = "";
                ServerNetConfig agentXml = AllocateAddress.allocate(userInfo.getUserId());
                if (agentXml != null) {
                    address = agentXml.getAddress();
                }
                resultObj.put("address", address);
                resultObj.put("time", System.currentTimeMillis() / 1000);
                resultObj.put("allowLogin", true);
                resultObj.put("isRegister", isRegister);
                boolean hasRole;
                if (StringUtils.isNullOrEmpty(userInfo.getNickName()) || 0 == userInfo.getSex()) {
                    hasRole = false;
                } else {
                    hasRole = true;
                }
                resultObj.put("hasRole", hasRole);
                resultObj.put(signKey, signValue);

                int checkLoginTokenOpen = ChannelConfig.CHECK_LOGIN_TOKEN_OPEN;
                if (checkLoginTokenOpen == 1) {
                    String loginToken = PlayerControl.matchOneLoginToken(userInfo.getUserId());
                    resultObj.put("loginToken", loginToken);
                }
            }
        }
        return resultObj;
    }

    private int getDefaultSetting() {
        int channelDefaultSetting = ChannelConfig.USER_DEFAULT_SETTING;
        int defaultSetting = 0;
        // Map<后台下标，服务端下标>
        Map<Integer, Integer> indexMap = new ConcurrentHashMap<>();
        indexMap.put(0, 1); // 位置
        indexMap.put(1, 0); // VIP
        for (Map.Entry<Integer, Integer> entry : indexMap.entrySet()) {
            defaultSetting |= (channelDefaultSetting >> entry.getKey() & 1) << entry.getValue();
        }
        return defaultSetting;
    }

    /**
    * 描述：是否APP渠道的appid
    * 作者：zrq
    * 时间：2023/8/24
    * 参数：

    * 返回值：
    **/
    private boolean isAppChannel(String appId){
        if(StringUtils.isNullOrEmpty(appId)){
            return false;
        }
        List<String> appIdList = StringUtils.stringToStringList(ChannelConfig.APP_CHANNEL_APPID, ";");
        return appIdList.contains(appId);
    }

    public static void main(String[] args) throws Exception {
        String appId = "10004";
        int game_id = 2006487560;
       int type = 1001;
        String uid = "201000150010235";
        int sid = 20100015;
        String secret = "8820f66327ff27f1d412b5c2dde76d6d";
        int time =(int) (System.currentTimeMillis() / 1000);
            SortedMap<String, String> paramMap = new TreeMap<>();
            paramMap.put("appid", appId);
            paramMap.put("game_id", String.valueOf(game_id));
        paramMap.put("type", String.valueOf(type));
        paramMap.put("uid", uid);
        paramMap.put("sid", String.valueOf(sid));
        paramMap.put("time", String.valueOf(time));
        StringBuilder sb = new StringBuilder();
        sb.append(secret).append(appId).append(game_id).append(uid).append(sid).append(type).append(time);
        String sign = MD5Security.md5(sb.toString()).toLowerCase();

        SortedMap<String, Object> xxxMap = new TreeMap<>();
        xxxMap.put("appid", appId);
        xxxMap.put("game_id", game_id);
        xxxMap.put("type", type);
        xxxMap.put("uid", uid);
        xxxMap.put("time", time);
        xxxMap.put("sid", sid);
        xxxMap.put("sign", sign);
        String s = JSON.toJSONString(xxxMap);

        String url = AppKeyMgr.getPlatformBaseUrl() + "/player/lineReport/" + AppKeyMgr.getAndroidAppId() + "/" + AppKeyMgr.getPlatformChannelId();
        String result = HttpHelper.doPostJson(url, s, "UTF-8");

        System.out.println(result);
    }
}
